<template>
    <el-scrollbar>
        <div class="pie-chart-main">
            <div class="left-box">
                <div class="title">
                    <div class="title-label">
                        <span class="title-label-text">企微获客渠道</span>
                        <el-tooltip effect="dark" placement="top-start">
                            <template #content>
                                <div>企微获客渠道统计筛选时间内首次添加员工企业微信的客</div>
                                <div>户数，并统计用户首次添加企微员工的方式。一个用户添</div>
                                <div>加多个员工，仅统计添加第一个员工企微时的添加时间和</div>
                                <div>添加方式。</div>
                            </template>
                            <span class="title-label-text-icon">
                                <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
                            </span>
                        </el-tooltip>
                    </div>
                    <div class="title-right">
                        <el-date-picker
                            v-model="formInfo.left_screen_time"
                            style="margin: 0 8px; width: 230px"
                            popper-class="title-times"
                            type="daterange"
                            :teleported="false"
                            :editable="false"
                            :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            range-separator="—"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :disabled-date="disabledDate"
                            @change="handleLeftTimeChange"
                            @calendar-change="calendarChange" />
                        <el-dropdown @command="handleLeftExport">
                            <el-button>导出</el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item :command="1"> 导出统计数据 </el-dropdown-item>
                                    <el-dropdown-item :command="2" @click="getClickEnevt">
                                        导出客户明细
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
                <div class="pie-box">
                    <div v-if="leftCharts" class="pie-box-content">
                        <div class="pie-box-chart">
                            <div ref="myRefLeft" class="chart_pie"></div>
                        </div>
                        <div class="legend-info">
                            <div class="legend-title">
                                <div class="legend-item-add">添加方式</div>
                                <div class="legend-item-proportion">占比</div>
                                <div class="legend-item-add-num">添加人数</div>
                            </div>
                            <div class="legend-list">
                                <div
                                    v-for="(item, index) in chartData.leftDataList"
                                    :key="index"
                                    class="legend-list-item">
                                    <div class="legend-item-add">
                                        <div class="item-icon" :style="{ background: pieColorList[index] }"></div>
                                        <div class="item-name">{{ item.name }}</div>
                                    </div>
                                    <div class="legend-item-proportion">{{ item.percent }}</div>
                                    <div class="legend-item-add-num">{{ item.value }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <el-empty v-if="!leftCharts" description="暂无数据"></el-empty>
                </div>
            </div>
            <div class="right-box">
                <div class="title">
                    <div class="title-label">
                        <span class="title-label-text">渠道活码获客场景</span>
                        <el-tooltip effect="dark" placement="top-start">
                            <template #content>
                                <div>渠道活码获客场景统计筛选条件下通过渠道活码首次添加</div>
                                <div>员工企业微信的客户数，并统计用户添加企微员工的场景。</div>
                                <div>一个用户通过渠道活码添加多个员工，仅统计添加第一个</div>
                                <div>员工企微时的添加时间和添加场景。</div>
                            </template>
                            <span class="title-label-text-icon">
                                <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
                            </span>
                        </el-tooltip>
                    </div>
                    <div class="title-right">
                        <el-date-picker
                            v-model="formInfo.right_screen_time"
                            style="margin: 0 8px; width: 230px"
                            popper-class="title-times"
                            type="daterange"
                            :teleported="false"
                            :editable="false"
                            :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            range-separator="—"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            :disabled-date="disabledDate2"
                            @change="handleRightTimeChange"
                            @calendar-change="calendarChange2" />
                        <el-dropdown @command="handleRightExport">
                            <el-button>导出</el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item :command="1"> 导出统计数据 </el-dropdown-item>
                                    <el-dropdown-item :command="2" @click="getClickEnevt">
                                        导出客户明细
                                    </el-dropdown-item>
                                    <el-dropdown-item :command="3"> 导出活码数据 </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>
                </div>
                <div class="pie-box">
                    <div v-if="rightCharts" class="pie-box-content">
                        <div class="pie-box-chart">
                            <div ref="myRefRight" class="chart_pie"></div>
                        </div>
                        <div class="legend-info">
                            <div class="legend-title">
                                <div class="legend-item-add">添加场景</div>
                                <div class="legend-item-proportion">占比</div>
                                <div class="legend-item-add-num">添加人数</div>
                            </div>
                            <div class="legend-list">
                                <div
                                    v-for="(item, index) in chartData.rightPageData"
                                    :key="index"
                                    class="legend-list-item">
                                    <div class="legend-item-add">
                                        <div class="item-icon" :style="{ background: pieColorList[index] }"></div>

                                        <el-tooltip
                                            :content="getChartsName(item?.name)"
                                            :disabled="disabled"
                                            placement="top">
                                            <div class="item-name" @mouseenter="handleMouse($event)">
                                                {{ getChartsName(item?.name) }}
                                            </div>
                                        </el-tooltip>
                                    </div>
                                    <div class="legend-item-proportion">{{ item.percent }}</div>
                                    <div class="legend-item-add-num">{{ item.value }}</div>
                                </div>
                            </div>
                            <div class="legend-page">
                                <div class="legend-page-back" @click="changePage(1)">
                                    <img
                                        v-if="pageInfo.page == 1"
                                        src="@/assets/customer/page_back_inactive_icon.png"
                                        alt="" />
                                    <img v-else src="@/assets/customer/page_back_icon.png" alt="" />
                                </div>
                                <div class="legend-page-current">{{ pageInfo.page }}/{{ nextPage }}</div>
                                <div class="legend-page-next" @click="changePage(2)">
                                    <img
                                        v-if="inactiveNext"
                                        src="@/assets/customer/page_next_inactive_icon.png"
                                        alt="" />
                                    <img v-else src="@/assets/customer/page_next_icon.png" alt="" />
                                </div>
                            </div>
                        </div>
                    </div>
                    <el-empty v-if="!rightCharts" description="暂无数据"></el-empty>
                </div>
            </div>
        </div>
    </el-scrollbar>
</template>
<script setup lang="ts">
import { ref, reactive, inject, nextTick, onMounted, computed } from 'vue';
import { getDay, downFile } from '@/utils/utils';
import {
    customerStatistics,
    customerStatisticsExport,
    customerStatisticsSyncExport,
    customerChannelInfo,
    customerChannelStatExport,
    customerChannelCustExport,
    liveCodeChannelExport
} from '@/api/customerCenter';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const echarts: any = inject('ec');

const myRefLeft = ref<any>(null);
const myRefRight = ref<any>(null);

const leftCharts = ref(false);
const rightCharts = ref(false);

const leftMaxNumLength = ref(1);
const rightMaxNumLength = ref(1);
const chartData = reactive({
    leftDataList: [],
    rightDataList: [],
    rightPageData: []
});

const pickDay = ref();
const pickDay2 = ref();

const formInfo = reactive({
    left_total_num: 0,
    right_total_num: 0,
    left_screen_time: [getDay(-7), getDay(-1, true)],
    right_screen_time: [getDay(-7), getDay(-1, true)]
});

const pieColorList = [
    '#FF724D',
    '#86DCA1',
    '#7791DA',
    '#DB65BB',
    '#FFD500',
    '#B8EA5C',
    '#48C871',
    '#665FFF',
    '#FF8585'
];
let clickEvent: any = null;
const getClickEnevt = e => {
    clickEvent = e;
};

const pageInfo = reactive({
    page: 1,
    pageSize: 9
});

const inactiveNext = computed(() => {
    return pageInfo.page * pageInfo.pageSize >= chartData.rightDataList.length;
});

const nextPage = computed(() => {
    return Math.ceil(chartData.rightDataList.length / pageInfo.pageSize);
});

const disabledDate = (time: any) => {
    if (!pickDay.value) {
        return time.getTime() > Date.now() - 3600 * 1000 * 24;
    }
    const con1 = new Date(pickDay.value).getTime() - 364 * 24 * 60 * 60 * 1000;
    const con2 = new Date(pickDay.value).getTime() + 364 * 24 * 60 * 60 * 1000;
    const con3 = time.getTime() > Date.now() - 3600 * 1000 * 24;
    return con3 ? con3 : time.getTime() < con1 || time.getTime() > con2;
};

const disabledDate2 = (time: any) => {
    if (!pickDay2.value) {
        return time.getTime() > Date.now() - 3600 * 1000 * 24;
    }
    const con1 = new Date(pickDay2.value).getTime() - 364 * 24 * 60 * 60 * 1000;
    const con2 = new Date(pickDay2.value).getTime() + 364 * 24 * 60 * 60 * 1000;
    const con3 = time.getTime() > Date.now() - 3600 * 1000 * 24;
    return con3 ? con3 : time.getTime() < con1 || time.getTime() > con2;
};

/**
 *
 */
const changePage = (type: number) => {
    if (type == 1) {
        if (pageInfo.page == 1) return;
        pageInfo.page--;
        chartData.rightPageData = chartData.rightDataList.slice(
            (pageInfo.page - 1) * pageInfo.pageSize,
            pageInfo.page * pageInfo.pageSize
        );
    } else if (type == 2) {
        if (inactiveNext.value) return;
        pageInfo.page++;
        chartData.rightPageData = chartData.rightDataList.slice(
            (pageInfo.page - 1) * pageInfo.pageSize,
            pageInfo.page * pageInfo.pageSize
        );
    }
};

/**
 * 企微获客渠道时间变动
 */
const handleLeftTimeChange = (val: any) => {
    if (!val) {
        pickDay.value = '';
        return;
    }
    initLeftData();
};

/**
 * 渠道活码获客场景时间变动
 */
const handleRightTimeChange = (val: any) => {
    if (!val) {
        pickDay2.value = '';
        return;
    }
    initRightData();
};

/**
 *
 */
const calendarChange = (val: Date[]) => {
    const [pointDay] = val;
    pickDay.value = pointDay;
};

const calendarChange2 = (val: Date[]) => {
    const [pointDay] = val;
    pickDay2.value = pointDay;
};

/**
 * 企微获客渠道-导出
 */
const handleLeftExport = (val: number) => {
    switch (val) {
        case 1:
            channelExport();
            break;
        case 2:
            channelSyncExport();
            break;
    }
};

/**
 * 渠道活码获客场景-导出
 */
const handleRightExport = (val: number) => {
    switch (val) {
        case 1:
            channelStatExport();
            break;
        case 2:
            channelCustExport();
            break;
        case 3:
            channelLiveCodeExport();
    }
};

/**
 * 导出企微获客渠道统计数据
 */
const channelExport = async () => {
    const params = {
        screen_time: formInfo.left_screen_time
    };
    const res = await customerStatisticsExport(params);
    downFile(res.file_url, res.file_name);
};

/**
 * 导出企微获客渠道客户明细数据
 */
const channelSyncExport = async () => {
    const params = {
        screen_time: formInfo.left_screen_time
    };
    const res = await customerStatisticsSyncExport(params);
    parabolaAnimation(clickEvent);
    res && ShowTaskMessage('导出客户明细异步任务创建成功');
};

/**
 * 导出渠道活码获客场景-统计数据
 */
const channelStatExport = async () => {
    const params = {
        screen_time: formInfo.right_screen_time
    };
    const res = await customerChannelStatExport(params);
    downFile(res.file_url, res.file_name);
};

/**
 * 导出渠道活码获客场景-客户明细
 */
const channelCustExport = async () => {
    const params = {
        screen_time: formInfo.right_screen_time
    };
    const res = await customerChannelCustExport(params);
    parabolaAnimation(clickEvent);
    res && ShowTaskMessage('导出客户明细异步任务创建成功');
};

/**
 * 导出渠道活码获客场景-活码数据
 */
const channelLiveCodeExport = async () => {
    const params = {
        screen_time: formInfo.right_screen_time
    };
    const res = await liveCodeChannelExport(params);
    downFile(res.file_url, res.file_name);
};

/**
 * 获取企微获取渠道数据
 */
const initLeftData = async () => {
    const params = {
        screen_time: formInfo.left_screen_time || []
    };
    const res = await customerStatistics(params);
    const list = res.list || [];
    if (list.length) {
        leftCharts.value = true;
    } else {
        leftCharts.value = false;
    }
    formInfo.left_total_num = res.total_num || 0;
    const ary: any = [];
    let leftMaxNum = 0;
    list.map(el => {
        ary.push({
            value: el.total,
            name: el.way_name,
            percent: el.percent
        });
        if (el.total > leftMaxNum) {
            leftMaxNum = el.total;
        }
    });

    leftMaxNumLength.value = String(leftMaxNum).length;
    chartData.leftDataList = ary;
    nextTick(() => {
        ary.length && getLeftEcharts(ary);
    });
};

/**
 * 获取渠道活码获客场景
 */
const initRightData = async () => {
    const params = {
        screen_time: formInfo.right_screen_time || []
    };
    const res = await customerChannelInfo(params);
    pageInfo.page = 1;
    const list = res.data || [];
    if (list.length) {
        rightCharts.value = true;
    } else {
        rightCharts.value = false;
    }
    formInfo.right_total_num = res.total_num || 0;
    const ary: any = [];
    let rightMaxNum = 0;
    list.map(el => {
        ary.push({
            value: el.num,
            name: `${el.group_id}-${el.group_name}`,
            percent: el.percent
        });
        if (el.num > rightMaxNum) {
            rightMaxNum = el.num;
        }
    });
    rightMaxNumLength.value = String(rightMaxNum).length;
    chartData.rightDataList = ary;
    chartData.rightPageData = ary.slice(0, pageInfo.pageSize);
    nextTick(() => {
        ary.length && getRightEcharts(ary);
    });
};

/**
 * 企微获客渠道echarts渲染
 * @param data 数据
 */
const getLeftEcharts = (data: any) => {
    let borderShow = 0;
    data.map((el: any) => {
        if (el.value) {
            borderShow++;
        }
    });
    const colorShow = data.every(el => !el.value);

    const chartsWidth = myRefLeft.value.getBoundingClientRect().width;
    let radiusList = ['40%', '55%'];
    if (chartsWidth < 300) {
        radiusList = ['50%', '65%'];
    }
    const myChartOne = echarts.init(myRefLeft.value);
    myChartOne.setOption({
        tooltip: {
            show: !colorShow,
            confine: true,
            trigger: 'item',
            formatter: function (parms) {
                let percentage = 0;
                for (let i = 0; i < data.length; i++) {
                    if (data[i].name === parms.name) {
                        percentage = data[i].percent;
                    }
                }
                const str = `${parms.marker} ${parms.data.name} ${percentage} ${parms.data.value}个`;
                return str;
            }
        },
        //
        series: [
            {
                name: '',
                type: 'pie',
                radius: radiusList,
                center: ['50%', '50%'],
                avoidLabelOverlap: false,
                silent: colorShow,
                data: data,
                label: {
                    normal: {
                        show: true,
                        position: 'center',
                        formatter: function () {
                            const name = '企微获客总数\r\n\r\n';
                            const arr = ['{a|' + name + '}', '{b|' + formInfo.left_total_num + '}'];
                            return arr.join('  ');
                        },
                        textStyle: {
                            rich: {
                                a: {
                                    fontSize: chartsWidth < 300 ? 12 : 14,
                                    color: '#666666'
                                },
                                b: {
                                    fontSize: chartsWidth < 300 ? 20 : 24,
                                    color: '#33302D',
                                    padding: [0, 8, 0, 0]
                                }
                            }
                        }
                    }
                },
                labelLine: {
                    show: false
                },
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: colorShow ? 0 : borderShow == 1 ? 0 : 2
                },
                color: colorShow ? '#F2F2F2' : pieColorList
            }
        ]
    });
    nextTick(() => {
        myChartOne.resize();
    });
    window.onresize = function () {
        myChartOne.resize();
    };
};

/**
 * 渠道活到码获客场景echarts渲染
 * @param data 数据
 */
const getRightEcharts = (data: any) => {
    let borderShow = 0;
    data.map((el: any) => {
        if (el.value) {
            borderShow++;
        }
    });

    const chartsWidth = myRefRight.value.getBoundingClientRect().width;
    const colorShow = data.every(el => !el.value);
    let radiusList = ['40%', '55%'];
    if (chartsWidth < 300) {
        radiusList = ['50%', '65%'];
    }
    const myChartTwo = echarts.init(myRefRight.value);
    myChartTwo.setOption({
        tooltip: {
            show: !colorShow,
            confine: true,
            trigger: 'item',
            formatter: function (parms) {
                let percentage = 0;
                for (let i = 0; i < data.length; i++) {
                    if (data[i].name === parms.name) {
                        percentage = data[i].percent;
                    }
                }
                const i = parms.data.name.indexOf('-');
                let name = '';
                if (i > -1) {
                    name = parms.data.name.slice(i + 1);
                }
                const str = `${parms.marker} ${name} ${percentage} ${parms.data.value}个`;
                return str;
            }
        },
        //
        series: [
            {
                name: '',
                type: 'pie',
                radius: radiusList,
                center: ['50%', '50%'],
                silent: colorShow,
                avoidLabelOverlap: false,
                data: data,
                label: {
                    normal: {
                        show: true,
                        position: 'center',
                        formatter: function () {
                            const name = '渠道活码获客总数\r\n\r\n';
                            const arr = ['{a|' + name + '}', '{b|' + formInfo.right_total_num + '}'];
                            return arr.join('  ');
                        },
                        textStyle: {
                            rich: {
                                a: {
                                    fontSize: chartsWidth < 300 ? 12 : 14,
                                    color: '#666666'
                                },
                                b: {
                                    fontSize: chartsWidth < 300 ? 20 : 24,
                                    color: '#33302D',
                                    padding: [0, 8, 0, 0]
                                }
                            }
                        }
                    }
                },
                labelLine: {
                    show: false
                },
                itemStyle: {
                    borderColor: '#fff',
                    borderWidth: colorShow ? 0 : borderShow == 1 ? 0 : 2
                },
                color: colorShow ? '#F2F2F2' : pieColorList
            }
        ]
    });
    nextTick(() => {
        myChartTwo.resize();
    });
    window.onresize = function () {
        myChartTwo.resize();
    };
};

const getChartsName = (name: any) => {
    const i = name.indexOf('-');
    let str = '';
    if (i > -1) {
        str = name.slice(i + 1);
    }
    return str;
};

const isBeyond = (e: any) => {
    const ev = window.event || e; // 浏览器兼容，最好写一下
    const textRange = (el: any) => {
        const textContent = el;
        const targetW = textContent.getBoundingClientRect().width;
        const range = document.createRange();
        range.setStart(textContent, 0);
        range.setEnd(textContent, textContent.childNodes.length);
        const rangeWidth = range.getBoundingClientRect().width;
        return rangeWidth > targetW;
    };
    return !textRange(ev.target); // target可以保证当前划过的dom节点一直保持是:el-tooltip__trigger
};
const disabled = ref(true);
const handleMouse = (e: any) => {
    disabled.value = isBeyond(e);
};
onMounted(() => {
    initLeftData();
    initRightData();
});
</script>
<style lang="scss" scoped>
$pie-min-height: 520px;

.pie-chart-main {
    margin-top: 16px;
    display: flex;
    justify-content: space-between;

    // align-items: center;
    .left-box {
        flex: 1;
        min-width: $pie-min-height;
        margin-right: 16px;
        background: #fff;
        border: 1px solid #eaeaea;
    }

    .right-box {
        flex: 1;
        min-width: $pie-min-height;
        background: #fff;
        border: 1px solid #eaeaea;
    }

    .title {
        padding: 14px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #eaeaea;

        .title-label {
            display: flex;
            align-items: center;
            font-size: 16px;
            font-family: PingFangSC-Medium, 'PingFang SC';
            font-weight: 500;
            color: #33302d;
            line-height: 22px;
            white-space: nowrap;

            .title-label-text-icon {
                display: inline-flex;
                margin-left: 8px;
                align-items: center;
                cursor: pointer;

                .el-icon {
                    margin-right: 2px;
                }
            }
        }

        .title-right {
            display: flex;
            align-items: center;

            .title-times {
                margin: 0 8px;
            }
        }
    }

    .pie-box {
        width: 100%;

        .pie-box-content {
            height: 375px;
            display: flex;
            justify-content: space-between;
        }

        .pie-box-chart {
            flex: 1;
            height: 100%;
        }

        .chart_pie {
            // width: 320px;
            width: 100%;
            height: 100%;
        }

        .legend-info {
            padding: 20px 0 17px;
            overflow: hidden;

            .legend-title {
                display: flex;
                align-items: center;
                font-size: 14px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #999;
                line-height: 20px;
            }

            .legend-item-add {
                width: 175px;
                display: flex;
                align-items: center;

                .item-icon {
                    margin: -1px 7px 0 0;
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                }

                .item-name {
                    width: 130px;

                    // padding-right: 14px;
                    overflow: hidden; /* 自动隐藏文字 */
                    text-overflow: ellipsis; /* 文字隐藏后添加省略号 */
                    white-space: nowrap; /* 强制不换行 */
                }
            }

            .legend-item-proportion {
                width: 90px;
            }

            .legend-item-add-num {
                min-width: 90px;
            }

            .legend-list {
                padding-top: 16px;
                min-height: 280px;

                .legend-list-item {
                    padding-bottom: 8px;
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, 'PingFang SC';
                    font-weight: 400;
                    color: #666;
                    line-height: 22px;
                    cursor: pointer;
                }
            }
        }

        .legend-page {
            margin-right: 20px;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .legend-page-back {
                width: 14px;
                height: 14px;
                cursor: pointer;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .legend-page-next {
                width: 14px;
                height: 14px;
                cursor: pointer;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .legend-page-current {
                margin: 0 4px;
                font-size: 14px;
                font-family: PingFangSC-Regular, 'PingFang SC';
                font-weight: 400;
                color: #33302d;
                line-height: 22px;
            }
        }
    }
}
</style>
